<template>
  <el-pagination
    @current-change="onPageChange"
    @size-change="onPageSizeChange"
    :page-sizes="[10, 20, 50, 100]"
    :total="iTotal"
    :current-page="iCurrentPage"
    :page-size="iPageSize"
    layout="total, sizes, prev, pager, next, jumper"
  ></el-pagination>
</template>

<script>
export default {
  name: 'zPagination', // 组件名
  inject: ['pagination'], //  接收后面mixins中provider的提供的参数
  props: {
    total: {
      // 总数
      type: Number,
      default: 0
    },
    currentPage: {
      // 当前页
      type: Number,
      default: 1
    },
    pageSize: {
      // 每页显示条数
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      iPageSize: this.pageSize,
      iCurrentPage: this.currentPage,
      iTotal: this.total
    }
  },
  watch: {
    pagination: {
      //  监听器
      deep: true,
      handler(v) {
        if (!v) {
          return
        }
        const { pageSize, total, currentPage } = v
        this.iPageSize = pageSize
        this.iTotal = total
        this.iCurrentPage = currentPage
        console.log(this.iPageSize)
        console.log(this.iTotal)
        console.log(this.iCurrentPage)
      }
    }
  },
  methods: {
    _emitPaginationChangeInfo() {
      // 触发父组件中特定的pageChanged函数
      console.log('触发父组件中特定的pageChanged函数')
      const pageInfo = {
        pageSize: this.iPageSize,
        currentPage: this.iCurrentPage
      }
      console.log(pageInfo)
      this.$emit('pageChanged', pageInfo)
    },
    onPageSizeChange(pageSize) {
      // 每页条数改变函数
      console.log('每页条数改变函数')
      const willMakePageChange = this.total / pageSize + 1 < this.iCurrentPage
      this.iPageSize = pageSize
      // 可能会造成页码改变发生，这时候不发送事件，因为可能造成事件死循环
      if (!willMakePageChange) {
        this._emitPaginationChangeInfo()
      }
    },
    onPageChange(currentPage) {
      //  页码改变函数
      console.log('页码改变函数')
      this.iCurrentPage = currentPage
      this._emitPaginationChangeInfo()
    }
  }
}
</script>
